package com.jackchong.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.MediaStore;
import android.provider.Settings;
import android.text.TextUtils;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.NetworkInterface;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

/**
 * Created by chong on 2017/9/20.
 */

public class PackageInfoUtils {

    //从相册
    public static final int ACTION_PICK_FROM_FILE = 1;
    //拍照后返回
    public static final int ACTION_PICK_FROM_CAMERA = 2;


    /**
     * 获取版本号(内部识别号 )
     * 失败为 return -1
     * @param context
     * @return
     */
    public static int getVersionCode(Context context) {
        try {
            PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return pi.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }

    public static String getUId(Context context){
        String androidID = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        String id = androidID + Build.SERIAL;
        return MD5Utils.MD5Encode(id);
    }


    /**
     * 获取MAC地址
     *
     * @param context
     * @return
     */
    public static String getMacAddress(Context context) {
        String mac = "02:00:00:00:00:00";
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            mac = getMacDefault(context);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            mac = getMacFromFile();
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            mac = getMacFromHardware();
        }
        return mac;
    }


    /**
     * Android  6.0 之前（不包括6.0）
     * 必须的权限  <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
     * @param context
     * @return
     */
    private static String getMacDefault(Context context) {
        String mac = "02:00:00:00:00:00";
        if (context == null) {
            return mac;
        }

        WifiManager wifi = (WifiManager) context.getApplicationContext()
                .getSystemService(Context.WIFI_SERVICE);
        if (wifi == null) {
            return mac;
        }
        WifiInfo info = null;
        try {
            info = wifi.getConnectionInfo();
        } catch (Exception e) {
        }
        if (info == null) {
            return null;
        }
        mac = info.getMacAddress();
        if (!TextUtils.isEmpty(mac)) {
            mac = mac.toUpperCase(Locale.ENGLISH);
        }
        return mac;
    }


    /**
     * Android 6.0（包括） - Android 7.0（不包括）
     * @return
     */
    private static String getMacFromFile() {
        String WifiAddress = "02:00:00:00:00:00";
        try {
            WifiAddress = new BufferedReader(new FileReader(new File("/sys/class/net/wlan0/address"))).readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return WifiAddress;
    }



    /**
     * 遍历循环所有的网络接口，找到接口是 wlan0
     * 必须的权限 <uses-permission android:name="android.permission.INTERNET" />
     * @return
     */
    private static String getMacFromHardware() {
        try {
            List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface nif : all) {
                if (!nif.getName().equalsIgnoreCase("wlan0")) continue;

                byte[] macBytes = nif.getHardwareAddress();
                if (macBytes == null) {
                    return "";
                }

                StringBuilder res1 = new StringBuilder();
                for (byte b : macBytes) {
                    res1.append(String.format("%02X:", b));
                }

                if (res1.length() > 0) {
                    res1.deleteCharAt(res1.length() - 1);
                }
                return res1.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "02:00:00:00:00:00";
    }


    /**
     * 用户看到的版本
     * 失败为 return ""
     * @return
     */
    public static String getVersionName(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            return info.versionName;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    public static boolean isOpenGPS(Context context) {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        if (locationManager != null){
            return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        }
        return false;
    }


    private String getAppName(Activity activity, int pID) {
        String processName = null;
        ActivityManager am = (ActivityManager) activity.getSystemService(activity.ACTIVITY_SERVICE);
        List l = am.getRunningAppProcesses();
        Iterator i = l.iterator();
        PackageManager pm = activity.getPackageManager();
        while (i.hasNext()) {
            ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo) (i
                    .next());
            try {
                if (info.pid == pID) {
                    CharSequence c = pm.getApplicationLabel(pm
                            .getApplicationInfo(info.processName,
                                    PackageManager.GET_META_DATA));
                    processName = info.processName;
                    return processName;
                }
            } catch (Exception e) {
            }
        }
        return processName;
    }


    /**
     * 服务是否在运行
     * @param serivce
     * @param context
     * @return
     */
    public static boolean isServiceRunning(Class serivce , Context context){

        final ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        final List<ActivityManager.RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE);
        for (ActivityManager.RunningServiceInfo runningServiceInfo : services) {
            if (runningServiceInfo.service.getClassName().equals(serivce.getName())){
                return true;
            }
        }
        return false;
    }


    public static void openPhoto(final Activity activity){

        AlertDialog.Builder builder = new AlertDialog.Builder(activity).setItems(new String[]{"从本地相册选择", "拍照"}, (dialog, which) -> {

            Intent intent = null;
            switch (which) {
                case 0:
                    intent = new Intent(Intent.ACTION_GET_CONTENT, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    intent.setType("image/*");
                    activity.startActivityForResult(intent, ACTION_PICK_FROM_FILE);
                    break;
                case 1:
                    intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    activity.startActivityForResult(intent, ACTION_PICK_FROM_CAMERA);
                    break;
            }
        });
        builder.create().show();
    }


    /**
     * 检测该包名所对应的应用是否存在
     * * @param packageName
     *
     * @return
     */
    public static boolean checkPackage(Context context, String packageName) {
        return checkPackage(context, packageName, false);
    }

    public static boolean checkPackage(Context context, String packageName, boolean isDownload) {
        if (packageName == null || "".equals(packageName)) return false;
        try {
            //手机已安装，返回true
            context.getPackageManager().getApplicationInfo(packageName, PackageManager.GET_UNINSTALLED_PACKAGES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            //手机未安装，跳转到应用商店下载，并返回false

            if (isDownload) {
                Uri uri = Uri.parse("market://details?id=" + packageName);
                Intent it = new Intent(Intent.ACTION_VIEW, uri);
                context.startActivity(it);
            }
            return false;
        }
    }


    /**
     * 跳转到天猫商品详情
     */
    public static void openTianmaoGoods(Context context, String goodsId){
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        String id = "539789035577";
        String url = "tmall://tmallclient/?{\"action\":”item:id=" + goodsId + "”}";
        Uri uri = Uri.parse(url);
        intent.setData(uri);
        context.startActivity(intent);
    }

    /**
     * 跳转到天猫店铺
     */
    public static void openTianmaoStore(Context context, String storeId){
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        String id = "539789035577";
        String url="tmall://page.tm/shop?shopId="+ storeId;
        Uri uri = Uri.parse(url);
        intent.setData(uri);
        context.startActivity(intent);
    }

    /**
     * 跳转到淘宝商品详情
     */
    public static void openTaobaoGoods(Context context, String goodsId){
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        String id = "539789035577";
        String url = "https://item.taobao.com/item.htm?id=" + goodsId + "&ali_refid=a3_430406_1007:1124066525:N:485184283370953001_0_100" +
                ":d45485b3013535b0cc4164b7cd5b7523&ali_trackid=1_d45485b3013535b0cc4164b7cd5b7523&spm=a21bo.50862.201874-sales.8.UYm99R";
        Uri uri = Uri.parse(url);
        intent.setData(uri);
        intent.setClassName("com.taobao.taobao", "com.taobao.tao.detail.activity.DetailActivity");
        context.startActivity(intent);
    }

    /**
     * 跳转到淘宝店铺
     */
    public static void openTaobaoStore(Context context, String storeId){
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        String url = "taobao://shop.m.taobao.com/shop/shop_index.htm?shop_id=" + storeId + "&spm=a230r.7195193.1997079397.8.Pp3ZMM&point" +
                "=%7B%22from%22%3A%22h5%22%2C%22url%22%3A%22http%3A%2F%2Fshop131259851.m.taobao.com%2F%22%2C%22h5_uid%22%3A%22aJHIDr" +
                "hLh0cCAYYbRtrrS3Ut%22%2C%22uaPoint%22%3A%22Mozilla%2F5.0%2520(Linux%3B%2520Android%25205.0.1%3B%2520SM-N9109W%2520Bui" +
                "ld%2FLRX22C%3B%2520wv)%2520AppleWebKit%2F537.36%2520(KHTML%2C%2520like%2520Gecko)%2520Version%2F4.0%2520Chrome%2F43" +
                ".0.2357.121%2520Mobile%2520Safari%2F537.36%2520Rong%2F2.0%22%7D";
        Uri uri = Uri.parse(url);
        intent.setData(uri);
        context.startActivity(intent);
    }

    /**
     * 跳转到京东商品详情
     */
    public static void openJingdongGoods(Context context, String goodsId){
        String id = "231023";//需要提取商品id，添加到下面url，不能单独将商品详情页作为url传入
        String url = "openapp.jdmobile://virtual?params=%7B%22sourceValue%22:%220_productDetail_97%22,%22des%22:%22productDetail%22," +
                "%22skuId%22:%22" + goodsId + "%22,%22category%22:%22jump%22,%22sourceType%22:%22PCUBE_CHANNEL%22%7D";
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        Uri uri = Uri.parse(url);
        intent.setData(uri);
        context.startActivity(intent);
    }
}
